import { createApp, defineComponent, h } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import {
  NConfigProvider,
  darkTheme,
  NGlobalStyle,
  NNotificationProvider
} from 'naive-ui'
import App from './App.vue'
import OutputService from './services/output.service'

const routes = Object.values(import.meta.glob('@/pages/**/router.ts', { eager: true, import: 'default' })) as Any[]
const router = createRouter({
  routes: [
    {
      path: '/:catchAll(.*)*',
      redirect: '/signin'
    },
    ...routes
  ],
  history: createWebHistory('./')
})
const outputService = new OutputService()

const app = createApp(defineComponent({
  setup () {
    return () => h(NConfigProvider, { theme: darkTheme }, {
      default: () => [
        h(NGlobalStyle),
        h(NNotificationProvider, {}, { default: () => h(App, { ref: 'rootRef' }) })
      ]
    })
  }
})).use(router)
const vm = app.mount('#app')
app.config.errorHandler = (err: Any) => {
  (vm.$refs.rootRef as Any)?.onError(err)
  outputService.error(err.message || err.toString?.() || err)
}
window.onunhandledrejection = evt => {
  evt.preventDefault?.()
  app.config.errorHandler?.(evt.reason, vm, '')
}
window.onerror = (evt: Any) => {
  evt.preventDefault?.()
  app.config.errorHandler?.(evt.error || evt, vm, '')
}
